class MK_animateSheet {
	constructor(arg = {}) {
		this.id = arg['id'];
		this.imgList = arg['imgList'];
		this.times = arg['times'];
		this.loop = arg['loop'];
		this.canvas = null;
		this.ctx = null;
		this.order = 0;
	}
	play() {
		const _self = this;
		const query = wx.createSelectorQuery();
		query
			.select(_self.id)
			.fields({
				node: true,
				size: true
			})
			.exec(res => {
				_self.canvas = res[0].node;
				_self.ctx = _self.canvas.getContext('2d');
				const dpr = wx.getSystemInfoSync().pixelRatio
				_self.canvas.width = res[0].width * dpr
				_self.canvas.height = res[0].height * dpr
				_self.ctx.scale(dpr, dpr)
				_self._begining();
			});
	}

	async _begining() {
		const _self = this;
		const dpr = wx.getSystemInfoSync().pixelRatio
		_self.ctx.clearRect(0, 0, _self.canvas.width, _self.canvas.height);
		_self.ctx.drawImage(_self.imgList[_self.order], 0, 0, _self.canvas.width/dpr, _self.canvas.height/dpr);
		if (_self.order < _self.imgList.length - 1) {
			await _self.timer();
			_self._begining();
		} else {
			_self.order = 0;
			if (_self.loop) _self._begining();
		}
	}

	timer() {
		const _self = this;
		return new Promise(function(resolve, reject) {
			setTimeout(function() {
				_self.order++;
				resolve();
			}, _self.times || 20);
		});
	}
}

export default MK_animateSheet
